//
//  StrategyPatternTest.m
//  DesignPattern
//
//  Created by orvibo on 2018/12/29.
//  Copyright © 2018 Alic. All rights reserved.
//

#import "StrategyPatternTest.h"
#import "CustomField.h"
#import "EmailValidator.h"
#import "PhoneNumberValidator.h"
#import "RegExCategories.h"

@implementation StrategyPatternTest

- (void)initEmailField {
    
    CustomField *emailField = [[CustomField alloc] init];
    emailField.text = @"4534345@qq.com";
    emailField.validator   = [[EmailValidator alloc]init];
    
    [self textFieldDidEndEditing:emailField];
}

- (void)initPhoneNmumberField{
    
    CustomField *phoneNumberField = [[CustomField alloc] init];
    phoneNumberField.text = @"电话号码";
    phoneNumberField.validator   = [[PhoneNumberValidator alloc]init];
    [self textFieldDidEndEditing:phoneNumberField];
}

#pragma mark - 验证算法 - 策略方式
- (void)textFieldDidEndEditing:(CustomField *)textField {
    
    CustomField *customField = (CustomField *)textField;
    
    if ([customField validate] == NO) {
        NSLog(@"输入不合法");
    }
}


#pragma mark - 验证算法 - 非策略模式
- (void)textFieldDidEndEditing2:(CustomField *)textField {
    
    BOOL isEmail = NO; // 判断输入框是否是email
    if (isEmail) {
        if ([self validateEmailInput:textField.text] == NO) {
            
            NSLog(@"输入不合法");
        }
    }else{
        if ([self validatePhoneNumberInput:textField.text] == NO) {
            
            NSLog(@"输入不合法");
        }
    }
    
}
// 相较于将这些判断逻辑现在现在vc里，明显使用这种策略模式会优雅简洁的多

- (NSString *)validateEmailInput:(NSString *)input {
    
    NSString *outString = nil;
    
    if (input.length <= 0) {
        
        outString = @"没有输入";
        
    } else {
        
        BOOL isMatch = [input isMatch:RX(@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}")];
        if (isMatch == NO) {
            
            outString = @"请输入正确的邮箱";
            
        } else {
            
            outString = nil;
        }
    }
    
    return outString;
}

- (NSString *)validatePhoneNumberInput:(NSString *)input {
    
    NSString *outString = nil;
    
    if (input.length <= 0) {
        
        outString = @"没有输入";
        
    } else {
        
        BOOL isMatch = [input isMatch:RX(@"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$")];
        if (isMatch == NO) {
            
            outString = @"请输入正确的手机号码";
            
        } else {
            
            outString = nil;
        }
    }
    
    return outString;
}
@end
